<template>
	<view class="page-container back-white pall-l col-box sb">
		<view class="content pall-base radius-base">
			<view class="row-box sb prow-s mb-base">
				<text>订单信息</text>
				<text class="s24 grey-light">订单编号：{{ merOrderNo }}</text>
			</view>
			<view class="prow-s">
				<cd-petcard-order :pet="pet" :showShop="false" :showArrow="false"></cd-petcard-order>
			</view>
			<view class="row-box sb prow-s" style="height: 88rpx;border-bottom: 1rpx solid #f2f2f2;">
				<view class="row-box">
					<text class="s24">换货原因</text>
					<text class="s24 red">*</text>
				</view>
				<view class="row-box pcol-base" @click.stop="showReason=true">
					<text v-if="reason.reason" class="s24">{{ reason.reason }}</text>
					<text v-else class="s24 grey-light">请选择换货原因</text>
					<u-icon class="ml-10" name="arrow-right" color="#333333" size="24"></u-icon>
				</view>
			</view>
			<view class="prow-s">
				<view class="row-box" style="height: 88rpx">
					<text class="s24">问题描述</text>
				</view>
				<textarea class="textarea" style="width: 100%;height: 188rpx;" v-model="description" :maxlength="100"
					placeholder-class="placeholder" placeholder="请详细说明问题..."
				>
				</textarea>
				<!-- 上传图片区域 -->
				<scroll-view scroll-x="true" style="white-space: nowrap;">
					<view class="pcol-l upload-grid">
						<view v-for="(item, index) in images" :key="index" class="upload-item">
							<image class="upload-image" :src="item" mode="aspectFill" @click.stop="previewImage(index, images)"></image>
							<view class="row-box center radius-circle icon-box">
								<u-icon name="close" color="#ffffff" size="28" :bold="true" @click.stop="removeImage(index)"></u-icon>
							</view>
						</view>
						<view v-if="images.length<limit" class="upload-item" @click="selectUploadHandle()">
							<image class="upload-image" src="/static/icon/upload.png" mode="aspectFill"></image>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- 换货原因弹窗 -->
		<u-select v-model="showReason" mode="single-column" value-name="id" label-name="reason"
			:confirm-color="primaryColor" title="选择换货原因" :list="reasonList" @confirm="selectReason"
		>
		</u-select>
		
		<!-- 提交按钮 -->
		<view class="submit-button-box" style="padding-top: 40rpx;">
			<view class="submit-button back-primary" @click="submitHandle()">提交换货申请</view>
		</view>
	</view>
</template>

<script>
	import env from '@/utils/env.js'
	export default {
		data() {
			return {
				merOrderNo: '', // 订单编号
				pet: {}, // 宠物对象
				showReason: false, // 是否展示换货原因弹窗
				reasonList: [], // 原因列表
				reason: {}, // 原因
				description: '', // 问题描述
				images: [], // 选择上传图片列表(临时地址)
				uploads: [],  // 照片列表(上传后)
				limit: 5, // 限制上传数量
				qntoken: '',  // 七牛云上传token
			};
		},
		watch: {
			// 侦听图片上传后地址列表
			uploads(newValue, oldValue) {
				if ((newValue.length == this.images.length) && this.images.length!=0) {
					// 上传完所有图片
					// 调用反馈接口
					this.submit()
				}
			},
		},
		onLoad(options) {
			this.merOrderNo = options.id
			this.pet = JSON.parse(decodeURIComponent(options.pet))
			// 获取七牛上传使用TOKEN
			this.getUploadToken()
			// 获取换货原因列表
			this.getReasonList()
		},
		methods: {
			// 选择换货原因弹窗
			selectReason(e) {
				console.log(e)
				this.reason['id'] = e[0].value
				this.reason['reason'] = e[0].label
			},
			
			// 选择上传前
			async selectUploadHandle() {
				this.images = [...this.images, ...await this.chooseImages(this.limit - this.images.length)]
			},
			
			// 提交申请处理
			submitHandle() {
				if (!this.reason.id) {
					return uni.showToast({
						icon: 'none',
						title: '未选择换货原因！'
					})
				} else if (!this.description) {
					return uni.showToast({
						icon: 'none',
						title: '未填写问题描述！'
					})
				}
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				// 获取临时文件列表长度
				const length = this.images.length
				if (length > 0) { // 如果用户选择了图片
					// 将选择的图片文件上传到存储空间（循环调用上传api）获得图片的访问地址
					this.images.forEach((filePath, index) => {
						let pathArr = filePath.split('.')
						// 获得唯一标识码
						let uniqueCode = this.generateUUID()
						// case 'ECN': uploadURL = 'https://up.qiniup.com'
						// case 'NCN': uploadURL = 'https://up-z1.qiniup.com'
						// case 'SCN': uploadURL = 'https://up-z2.qiniup.com'
						// case 'NA': uploadURL = 'https://up-na0.qiniup.com'
						// case 'ASG': uploadURL = 'https://up-as0.qiniup.com'
						uni.uploadFile({
							url: 'https://up-z2.qiniup.com',
							filePath: filePath,
							name: 'file',
							formData: {
								'key': uniqueCode + '.' + pathArr[pathArr.length-1],
								'token': this.qntoken,
							},
							success: (res) => {
								console.log('uni.uploadFile', res)
								let strToObj = JSON.parse(res.data)
								let backUrl = env.imageUrl + strToObj.key
								// 处理上传成功后的返回值
								this.uploads.push(backUrl)
							},
							fail: (err) => {
								console.log('uni.uploadFile', err)
							}
						})
					})
				} else { // 用户未选择图片
					// 调用提交申请
					this.submit()
				}
			},
			// 提交申请
			submit() {
				let params = {}
				params['orderNo'] = this.merOrderNo
				params['reasonId'] = this.reason.id
				params['description'] = this.description
				if (this.uploads.length) params['images'] = this.uploads.join(',')
				this.$api.AddAfterSales(params).then(res => {
					console.log('AddAfterSales-success', res)
					uni.hideLoading()
					if (res.data.code == 200) {
						uni.showToast({
							icon: 'none',
							title: '提交成功！',
							success: () => {
								setTimeout(() => {
									uni.navigateBack({
										delta: 1,
										success: () => {
											uni.startPullDownRefresh()
										}
									})
								}, 300)
							}
						})
					}else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				}).catch(err => {
					console.log('AddAfterSales-fail', err)
					uni.hideLoading()
				})
			},
			
			// 获取换货原因列表
			getReasonList() {
				this.$api.GetReasonList().then(res => {
					console.log('GetReasonList-success', res)
					if (res.data.code == 200) {
						this.reasonList = res.data.data.records
					}else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				}).catch(err => {
					console.log('GetReasonList-fail', err)
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	// 订单信息
	.content {
		box-shadow: 0rpx 4rpx 46rpx 0rpx rgba(227,230,229,0.8);
		// 多行文本输入框
		.textarea {
			fontSize: 24rpx;
			color: #333333;
			line-height: 36rpx;
		}
		.placeholder {
			fontSize: 24rpx;
			color: #999999;
			line-height: 36rpx;
		}
	}
	
</style>
